package demo3;
import java.util.HashMap;
import java.util.Map;

class Product {
    int id;
    String name;
    double price;

    public Product(int id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Product product = (Product) o;
        return id == product.id;
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(id);
    }
}

class InventoryService {
    static Map<Product, Integer> stock = new HashMap<>();

    static int getStock(Product product) {
        return stock.getOrDefault(product, 0);
    }
}

public class ShoppingCartSystem {
    Map<Product, Integer> cart = new HashMap<>();

    public void addProduct(Product product, int quantity) {
        if (InventoryService.getStock(product) < quantity) {
            throw new IllegalArgumentException("商品库存不足");
        }
        cart.merge(product, quantity, Integer::sum);
    }

    public void removeProduct(Product product, int quantity) {
        if (cart.containsKey(product)) {
            int newQuantity = cart.get(product) - quantity;
            if (newQuantity <= 0) {
                cart.remove(product);
            } else {
                cart.put(product, newQuantity);
            }
        }
    }

    public double calculateTotal() {
        return cart.entrySet().stream()
                .mapToDouble(entry -> entry.getKey().price * entry.getValue())
                .sum();
    }

    public static void main(String[] args) {
        ShoppingCartSystem cartSystem = new ShoppingCartSystem();
        Product product1 = new Product(1, "手机", 5000);
        InventoryService.stock.put(product1, 10);
        cartSystem.addProduct(product1, 2);
        System.out.println("购物车总金额: " + cartSystem.calculateTotal());
        cartSystem.removeProduct(product1, 1);
        System.out.println("移除部分商品后购物车总金额: " + cartSystem.calculateTotal());
    }
}